<?php
require_once('include/db.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST')
    die("Method not allowed.");

$request = file_get_contents("php://input");

$tmp = explode('|', $request);
$assoc = array();

foreach ($tmp as $item)
{
    $item = explode('=', $item);
    $assoc[$item[0]] = $item[1];
}


if (!isset($assoc['token']))
    die("Token not given.");

$device_id = get_device_id($assoc['token']);
if ($device_id === false)
    die("Token not found.");

$latitude = null;
$longitude = null;

for ($i = 0; ; $i++)
{
    if (!isset($assoc["name$i"]) || !isset($assoc["type$i"]) || !isset($assoc["value$i"]))
        break;
    if ($assoc["type$i"] == "latitude")
    {
        $latitude = $assoc["value$i"];
    }
    else if ($assoc["type$i"] == "longitude")
    {
        $longitude = $assoc["value$i"];
    }
    else insert_data(
        $device_id, $assoc["name$i"], $assoc["type$i"], $assoc["value$i"],
        isset($assoc["unit$i"])?$assoc["unit$i"]:''
    );
}

if (!is_null($latitude) && !is_null($longitude)) {
    insert_location($device_id, $latitude, $longitude);
}

echo "Success.";
